//
//  UIBarButtonItem+Extension.swift
//  weiBo项目准备
//
//  Created by 鲜世杰 on 16/5/11.
//  Copyright © 2016年 鲜世杰. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

let WeiboAppKey = "932099285"

let WeiboRedirect_Uri = "http://www.baidu.com"

let WeiboAppSecret = "c5526873eeeb8a8b0b24bfcaa73ec751"

class XSJOAuthViewController: UIViewController {
    
    private lazy var webView : UIWebView = UIWebView()
    
    override func loadView() {
//        webView.delegate = self
        webView.delegate = self
        view = webView
    }
    override func viewDidLoad() {
        setupNavUI()
        
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
//        let url = "https://www.baidu.com"
        let requst = NSURLRequest(URL: NSURL(string: url)!)
        webView.loadRequest(requst)
    }
    
    
    private func setupNavUI (){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 15, target: self, action: "autoFillAction")
        navigationItem.title = "微博登陆"
        
    }
    @objc private func cancelAction() {
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    @objc private func autoFillAction() {
        
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '18408226618'; document.getElementById('passwd').value = 'xianshijie+5683'")
        
    }
//
//    private func requestAccessToken (code : String) {
//        
//        
//       
//        
//        let url = "https://api.weibo.com/oauth2/access_token"
//        let prame = [
//            
//            "client_id" : weiboAppKey,
//            "client_secret" : weiboAppSecret,
//            "grant_type": "authorization_code",
//            "code" : code,
//            "redirect_uri" : WeiboRedirect_Uri
//            
//        ]
//        let sessionManager = AFHTTPSessionManager()
//        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        sessionManager.POST(url, parameters: prame, constructingBodyWithBlock: nil, success: { (_, response) -> Void in
//            
//            guard let dic = response as? [String : AnyObject] else{
//                
//                print("json格式不正确")
//                
//                return
//            }
//            let userAccount = XSJUserAocut(dic: dic)
//            print(response)
//            
//            }) { (_, error) -> Void in
//                print(error)
//        }
//        
//        
//    }
//    
//    
//    private func requestUserInfo(userAccount : XSJUserAocut) {
//        
//        let url = "https://api.weibo.com/2/users/show.json"
//        let params = [
//            "access_token": userAccount.access_token!,
//            "uid": "\(userAccount.uid)"
//        ]
//        let sessionManager = AFHTTPSessionManager()
//        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        sessionManager.GET(url, parameters: params, progress: nil, success: { (_, response) -> Void in
//            
//            guard let dic = response as? [String: AnyObject] else {
//                print("不是一个正确的json数据")
//                return
//            }
//            
//            
//            userAccount.name = dic["name"] as? String
//            userAccount.avatar_large = dic["avatar_large"] as? String
//            
//            print(userAccount)
//            
//            }) { (_, error) -> Void in
//                print(error)
//        }
//        
//    }
//    
//    
}
extension XSJOAuthViewController: UIWebViewDelegate {
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        
//        print(request.URL?.absoluteString)
        
        guard let url = request.URL else {
            
            return false
            
        }
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
            
            
            return true
        }
        if let query = url.query where query.hasPrefix("code=") {
            
            let code = query.substringFromIndex("code=".endIndex)
//            print(code)
            //requestAccessToken(code)
            XSJUserAccountViewModel.sharedUserAccount.requestAccessToken(code, complete: { (isSuccess) -> () in
                if isSuccess {
                    print("登陆成功")
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                    })
                } else {
                    SVProgressHUD.showErrorWithStatus("登陆失败")
                }
            })
        }else{
        
            dismissViewControllerAnimated(true, completion: nil)
            
        }
        
        return false
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
}

